
//
//  HomeDeliveryRangeController.m
//  FD
//
//  Created by xiaofang wang on 2018/11/27.
//  Copyright © 2018年 ZhiYuan Network. All rights reserved.
//  @"查看配送范围"

#import "HomeLookDeliveryRangeController.h"

//model
#import "HomeLookDeliveryRangeModel.h" //大
#import "HomeLatLngListModel.h"///中
#import "HomeCoordinateModel.h" //小

//view
#import "HomeSearchTextView.h" //自定义输入框view
#import "FDAlertView.h" //2019-1-15 废弃不要了
#import "HomeLookRangeBottomView.h"

//contrtoller

//helper & tool
#import "HomeLookDeliveryRangeHelper.h"
#import "CCLocation.h"

//google地图
#import <GoogleMaps/GoogleMaps.h>
#import <GooglePlaces/GooglePlaces.h>
#import <GoogleMaps/GMSGeometryUtils.h>



@interface HomeLookDeliveryRangeController ()<GMSMapViewDelegate,
GMSAutocompleteTableDataSourceDelegate,
HomeSearchTextViewDelegate>
/**google地图*/
@property (nonatomic, strong) GMSMapView *mapView;
/**谷歌地图自送搜索数据源类*/
@property (nonatomic, strong) GMSAutocompleteTableDataSource *tableDataSource;
/**搜索结果控制器*/
@property (nonatomic, strong) UITableViewController *resultControler;
/**搜索框*/
@property (nonatomic, strong) HomeSearchTextView *searchView;

/**弹框*/
@property (nonatomic, strong) FDAlertView *fdAlertView;


//2019-1-13 android 获取地图中心点的经纬度坐标
/**这个是屏幕中心点*/
//@property (nonatomic, strong) GMSMarker *mylocationMarker;
/**底部view(是否在配送范围之内+立即点餐按钮)*/
@property (nonatomic, strong) HomeLookRangeBottomView *bottomView;

/**2019-1-14屏幕中心绿色的图标*/
@property (nonatomic, strong) UIImageView *centerGreenAddressImageView;

/**标记rect数组 用户判断是否在配送范围之内
 2019-2-26请参考接口返回数据
 rectArrM的数据结构应该是这样的[[{},{},{}],[{},{}],[{}]]
 数组里面套数组。
 */
@property (nonatomic, strong) NSMutableArray <NSArray *>*rangeRectArrayM;

/**数据源数组 配合rectArrM使用,用于判断由谁进行配送*/
@property (nonatomic, strong) NSMutableArray <HomeLookDeliveryRangeModel *>*dataArrayM;

@end


@implementation HomeLookDeliveryRangeController

#pragma mark - 一 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = NSLocalizedString(L_Home_LookRange, @"查看配送范围");
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self loadRangeListDataAndLocation];
   
    [self setupUI];
}


/**
 适配iphoneX
 导航条 navH
 输入框 40
 地图   h - navH - 40
 */
- (void)setupUI {
    [self setupMapView];

    [self setupSearchView];
    
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(44*2);
        make.bottom.equalTo(self.view.mas_bottom).offset(-FD_TabbarSafeBottomMargin);
    }];
}
- (void)setupMapView {
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:51.90027
                                                            longitude:-8.55794
                                                                 zoom:11];
    self.mapView = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    self.mapView.delegate = self; //设置代理
//    self.mapView.settings.compassButton = YES;
//    self.mapView.settings.myLocationButton = YES;
    
    CGFloat mapView_y = FD_NavH + 40;
    CGFloat mapView_h = SCREEN_HEIGHT - mapView_y - FD_TabbarSafeBottomMargin - 44*2;
    self.mapView.frame = CGRectMake(0, mapView_y, SCREEN_WIDTH, mapView_h);

    [self.view addSubview:self.mapView];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.mapView.myLocationEnabled = YES;
    });
    
    [self.mapView addSubview:self.centerGreenAddressImageView];
    [self.centerGreenAddressImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(20, 27));
        make.centerY.equalTo(self.mapView.mas_centerY);
        make.centerX.equalTo(self.mapView.mas_centerX);
    }];
    
//    //当前定位位置
//    GMSMarker *mylocationMarker = [[GMSMarker alloc] init];
//    mylocationMarker.title = @"需求你明白了吗？";
//    mylocationMarker.position  = CLLocationCoordinate2DMake(51.90027, -8.55794);
//    mylocationMarker.appearAnimation = kGMSMarkerAnimationPop;
//    mylocationMarker.flat = YES;
//    mylocationMarker.draggable = YES;
//    mylocationMarker.groundAnchor = CGPointMake(0.5, 0.5);
//    mylocationMarker.icon = [UIImage imageNamed:@"当前位置"];
//    mylocationMarker.map = self.mapView;
//    self.mylocationMarker = mylocationMarker;
}

//!!!!: 加载到数据
- (void)loadRangeListDataAndLocation {
    //定位
    [[CCLocation shareInstance] requestPermission];
    
    [[CCLocation shareInstance] updateLocationWithDesiredAccuracy:(kCLLocationAccuracyHundredMeters) block:^(CLLocation *location) {

        //移动地图到当前位置
        GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude zoom:12];
        GMSCameraUpdate *update = [GMSCameraUpdate setCamera:camera];
        [self.mapView moveCamera:update];
        
    } fail:^(NSError *error) {
        FDLog(@"定位失败:%@",[error localizedDescription]);
    }];
    
    
    //2.请求数据
    [HomeLookDeliveryRangeHelper loadHomeLookDeliveryRangeDataComplection:^(NSArray * _Nonnull arr) {
        
        if (!arr.count) { return ; }
        
        self.dataArrayM = [arr mutableCopy];
        
        for (HomeLookDeliveryRangeModel *lookRangeModel  in arr) {
            //1.绘制图形
            //坑:服务器返回的是一个二维坐标数组,每个数组都要单独绘制一次,
            [self fdDrawPolygonWithArr:lookRangeModel.positionList];
            
            //2.设置大头针
            [self createMarkerWithHomeCoordinateModel:lookRangeModel];
        }
        //坑2:zoom 文档上说的不清楚,经过测试 11比较合适。
    }];
}

- (void)setupSearchView {

    //h ： 40
    self.searchView.frame = CGRectMake(0, FD_NavH, SCREEN_WIDTH, 40);
    [self.view addSubview:self.searchView];
    
    //google自动搜索数据源
    self.tableDataSource = [[GMSAutocompleteTableDataSource alloc] init];
    self.tableDataSource.delegate = self; //设置代理GMSAutocompleteTableDataSourceDelegate

    //限制搜索结果
    GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
    filter.country = @"IE"; //(只搜索爱尔兰国的)
    self.tableDataSource.autocompleteFilter = filter; 
    
    
    //搜索结果控制器
    self.resultControler = [[UITableViewController alloc] init];
    self.resultControler.tableView.delegate = self.tableDataSource;
    self.resultControler.tableView.dataSource = self.tableDataSource;
}

#pragma mark - 二 getter
- (UITableViewController *)resultControler {
    if (!_resultControler) {
        
        //创建对象
        _resultControler = [[UITableViewController alloc] init];
        //设置代理对象
        _resultControler.tableView.delegate = self.tableDataSource;
        _resultControler.tableView.dataSource = self.tableDataSource;
    }
    return _resultControler;
}

- (HomeSearchTextView *)searchView {
    if (!_searchView) {
        _searchView = [[HomeSearchTextView alloc] initWithFrame:CGRectZero];
        //设置代理
        _searchView.delegate = self; //
    }
    return _searchView;
}


- (FDAlertView *)fdAlertView {
    if (!_fdAlertView) {
        _fdAlertView = [[FDAlertView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    }
    return _fdAlertView;
}
- (HomeLookRangeBottomView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[HomeLookRangeBottomView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44*2)];
        FDWeakSelf;
        
        _bottomView.clickInstantOrderBlock = ^{
            [weakSelf.navigationController popViewControllerAnimated:YES]; //原路返回
        };
    }
    return _bottomView;
}

- (UIImageView *)centerGreenAddressImageView {
    if (!_centerGreenAddressImageView) {
        _centerGreenAddressImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dizhi2"]];
    }
    return _centerGreenAddressImageView;
}

- (NSMutableArray<NSArray *> *)rangeRectArrayM {
    if (!_rangeRectArrayM) {
        _rangeRectArrayM = [NSMutableArray array];
    }
    return _rangeRectArrayM;
}


- (NSMutableArray<HomeLookDeliveryRangeModel *> *)dataArrayM {
    if (!_dataArrayM) {
        _dataArrayM = [NSMutableArray array];
    }
    return _dataArrayM;
}

#pragma mark - 三 HomeSearchTextViewDelegate

//点击了输入框
- (void)homesearchTextFieldDidChange:(UITextField *)tf {
    //输入框内容发生变回就会触发该方法
    //触发搜索回调方法
    [self.tableDataSource sourceTextHasChanged:tf.text];
}

//开始输入
- (void)homesearchTextViewDidBeginEditing:(UITextField *)textField {
    [self fdShowResultViewController];
}

//结束输入
- (void)homesearchTextViewDidEndEditing:(UITextField *)textField {
    [self fdHideResultViewController];
}


#pragma mark - 三 GMSMapViewDelegate
- (void)mapView:(GMSMapView *)mapView didTapMyLocation:(CLLocationCoordinate2D)location {

    FDLog(@"点击的坐标点是:经度:%f---纬度:%f",location.latitude,location.longitude);
}

//!!!!:滚动地图
- (void)mapView:(GMSMapView *)mapView didChangeCameraPosition:(GMSCameraPosition *)position {
    CLLocationCoordinate2D coordinate = position.target;
    //2.判断是否在配送范围中
    [self judgeIsInDeliveryRangeWithLocation:coordinate];
    
//    self.mylocationMarker.position = coordinate;
}


//!!!!:结束滚动
- (void)mapView:(GMSMapView *)mapView idleAtCameraPosition:(GMSCameraPosition *)position {
    FDLog(@"经度:%f--纬度:%f",position.target.latitude,position.target.longitude);
    //调接口:坐标转换为地址。
    CLLocationCoordinate2D coordinate = position.target;
    
//    android
//        ss.append("https://maps.googleapis.com/maps/api/geocode/json?");
//        ss.append("latlng=" + lastlatitude + "," + lastlongitude);
//        ss.append("&key=" + "AIzaSyDU8SBtzx84CB2gf2kfZhC_Y9BRP6U7znw");

    
    NSString *urlStr = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&key=%@",coordinate.latitude,coordinate.longitude,kGoogleMapAPIKey];
    FDLog(@"googleapi:%@",urlStr); //https://maps.googleapis.com/maps/api/geocode/json?latlng=51.900270,-8.557940&key=AIzaSyDU8SBtzx84CB2gf2kfZhC_Y9BRP6U7znw

    //1.更新marker位置
//    self.mylocationMarker.position = coordinate; //显示定位坐标点
    
    //get请求
    [FDHttpAPi requestGoogleAPIReverseGeocodeUrl:urlStr successBlock:^(NSString *address) {
        FDLog(@"%@",[NSThread currentThread]);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.searchView homesearchViewUpdateTFStr:address placeholder:@""];
        });
    } failBlock:^(NSError *error) {
        FDLog(@"%@",error);
    }];
}

#pragma mark - 三 GMSAutocompleteTableDataSourceDelegate

//!!!!:搜索
//@required点击搜索结果代理上面的cell的时候会被调用
//要干什么:回收键盘,给textField赋值,隐藏搜索结果控制器
- (void)tableDataSource:(GMSAutocompleteTableDataSource *)tableDataSource
didAutocompleteWithPlace:(GMSPlace *)place {
    FDLog(@"xxxx:%@--%@",place.name,place.formattedAddress);
    
    [self.searchView homesearchViewResignFirstResponser]; //回收键盘
    [self.searchView homesearchViewUpdateTFStr:place.formattedAddress placeholder:@""];
    [self fdHideResultViewController]; //隐藏搜索结果控制器
    
//    self.mylocationMarker.position = place.coordinate; //1-15
    
    //显示是否在配送范围之内结果
    NSString *resultStr = NSLocalizedString(L_Home_BZSHQY, @"这不在我们的送货区域(支持自提)");
    if ([self judgeIsInDeliveryRangeWithLocation:place.coordinate]) {
        resultStr = NSLocalizedString(L_Home_InRange, @"在配送范围之内");
        [self.bottomView updateDeliveryRangeLabelTitle:resultStr];
    }
    
    //更新camera
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:place.coordinate.latitude
                                                            longitude:place.coordinate.longitude
                                                                 zoom:12];
    GMSCameraUpdate *cameraUpdate = [GMSCameraUpdate setCamera:(camera)];
    [self.mapView moveCamera:(cameraUpdate)];
}


//判断是否在配送范围之内
- (BOOL)judgeIsInDeliveryRangeWithLocation:(CLLocationCoordinate2D)point {
    

    if (!self.dataArrayM.count) {
        FDLog(@"数据组为空直接返回NO");
        return NO;
    }
    
    //2019-2-26重写，这种方式效率很差，先实现功能。
    
    //第一步:数据转换
    //需要转换成如下JSON数据格式 @"name"  @"pathArr"
//        [{"name":"xxx店","pathArr":["path1","path2"]},{"name":"yyy店","pathArr":["p21","p22"]}]
    NSMutableArray *newBigArrM = [NSMutableArray array];
    
    for (HomeLookDeliveryRangeModel *firstLevelModel in self.dataArrayM) {
        NSMutableDictionary *bigDicM = [NSMutableDictionary dictionary];
        [bigDicM setValue:firstLevelModel.name forKey:@"name"];
        NSMutableArray *pathArr = [NSMutableArray array];
        
        for (HomeLatLngListModel *secondLevelModel in firstLevelModel.positionList) {
            GMSMutablePath *secPath = [GMSMutablePath path];
            for (HomeCoordinateModel *thirdLevelModel in secondLevelModel.latLngList) {
                [secPath addCoordinate:thirdLevelModel.coordinate2D];
            }
            [pathArr addObject:secPath];
        }
        
        [bigDicM setValue:pathArr forKey:@"pathArr"];
        
        [newBigArrM addObject:bigDicM];
    }
    
    
    //第二步:判断是否在配送范围之内假设不在
    BOOL shifouZaiFanweinei = NO; //假设不在

    for (NSDictionary *convertDic in newBigArrM) {
        NSArray *pArr = convertDic[@"pathArr"];
        for (GMSMutablePath *path in pArr) {
            
            //调用Google接口判断是否在配送范围之内
            BOOL isIn = GMSGeometryContainsLocation(point, path, YES);
            if (isIn) {
                shifouZaiFanweinei = YES;

                NSString *deliverString = [NSString stringWithFormat:@"Your order will be delivered by %@",convertDic[@"name"]];
                [self.bottomView updateDeliveryRangeLabelTitle:deliverString];

                break;
            }
        }
    }
    
    //展示:不在配送范围之内
    if (!shifouZaiFanweinei) {
        [self.bottomView updateDeliveryRangeLabelTitle:NSLocalizedString(L_Home_BZSHQY, @"这不在我们的送货区域(支持自提)")];
    }

    return shifouZaiFanweinei;
}



//- (BOOL)judgeIsInDeliveryRangeWithLocation:(CLLocationCoordinate2D)point {
//
//    //判断是否在配送范围之内
//    /**
//     1.Google地图提供的判断是否在范围内方法: BOOL GMSGeometryContainsLocation(CLLocationCoordinate2D point, GMSPath *path, BOOL geodesic);
//     2.定义一个数组保存所有的 path 到 self.rectArrM
//     3.遍历 self.rectArrM 只有一个在范围内，break, 标记在范围内,反之一直走。
//     */
//    BOOL shifouZaiFanweinei = NO; //假设不在
////    for(int i=0; i<self.rectArrM.count; i++) {
////
////        NSArray *innerArr = self.rectArrM[i];
////
////        //判断是否在范围之内
////        for (GMSPath *path in innerArr) {
////
//            BOOL isIn = GMSGeometryContainsLocation(point, path, YES);
////            if (isIn) { //只有一个在---->在
////                shifouZaiFanweinei = YES; //标记为真
////
////                //展示由谁进行配送
//                HomeLookDeliveryRangeModel *bigmodel =  self.dataArrayM[i];
//                NSString *deliverString = [NSString stringWithFormat:@"Your order will be delivered by %@",bigmodel.name];
//                [self.bottomView updateDeliveryRangeLabelTitle:deliverString];
////
////                break; //结束循环
////            }
////        }
////    }
////
//    //展示:不在配送范围之内
//    if (!shifouZaiFanweinei) {
//        [self.bottomView updateDeliveryRangeLabelTitle:NSLocalizedString(L_Home_BZSHQY, @"这不在我们的送货区域(支持自提)")];
//    }
////
////
////    //返回bool值结果,因为搜索框也要判断是否在配送范围之内。
//    return shifouZaiFanweinei;
//}


//@required
//要干什么:回收键盘
- (void)tableDataSource:(GMSAutocompleteTableDataSource *)tableDataSource
didFailAutocompleteWithError:(NSError *)error {
    FDLog(@"yyyy:%@",[error localizedDescription]);
}


//调用了 [weakSelf.tableDataSource sourceTextHasChanged:searchStr];
//这行代码会被触发:请求搜索数据
//要干什么:reloadData，显示菊花
- (BOOL)tableDataSource:(GMSAutocompleteTableDataSource *)tableDataSource
    didSelectPrediction:(GMSAutocompletePrediction *)prediction {
    RBFunctionLog
    return YES;
}


//请求到数据的回调
//加载数据显示菊花
- (void)didRequestAutocompletePredictionsForTableDataSource:
(GMSAutocompleteTableDataSource *)tableDataSource {
    RBFunctionLog
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [self.resultControler.tableView reloadData];
}

//要干什么:回收键盘,隐藏菊花
- (void)didUpdateAutocompletePredictionsForTableDataSource:(GMSAutocompleteTableDataSource *)tableDataSource {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self.resultControler.tableView reloadData];
}


#pragma mark - 四 private
// 绘制地图
//传入一个数组坐标绘制一个图形 这个方法会被调用 n 次
- (void)fdDrawPolygonWithArr:(NSArray <HomeLatLngListModel *>*)positionList {

    //这个的作用是方便后面判断:是否在配送范围之内
    // NSMutableArray
    NSMutableArray *innerArrM = [NSMutableArray array].mutableCopy;

    for (HomeLatLngListModel *latlngModel in positionList) {
        NSArray *latLngListArr = latlngModel.latLngList;
        //创建path
        GMSMutablePath *smallPath = [GMSMutablePath path];
    
        //添加坐标
        for (HomeCoordinateModel *coordinateModel in latLngListArr) {
            [smallPath addCoordinate:coordinateModel.coordinate2D];
        }

        [innerArrM addObject:smallPath];

        //循环绘制
        GMSPolygon *polygon = [GMSPolygon polygonWithPath:smallPath];
        polygon.fillColor = rgba(78, 180, 111, 0.8); // #4eb46f
        polygon.strokeColor = rgba(78, 180, 111, 0.8); // #4eb46f
        
        
        polygon.strokeWidth = 2.0;
        polygon.map = self.mapView;
    }
    
    //保存 bigPath 方便后面判断是否在配送范围之内
//    [self.rectArrM addObject:bigPath];
    [self.rangeRectArrayM addObject:[innerArrM copy]];
}


/**创建Marker*/
- (void)createMarkerWithHomeCoordinateModel:(HomeLookDeliveryRangeModel *)model {
    GMSMarker *mylocationMarker = [[GMSMarker alloc] init];
    mylocationMarker.title = model.name;
    mylocationMarker.position  = model.currentCoordinate;
    mylocationMarker.appearAnimation = kGMSMarkerAnimationPop;
    mylocationMarker.flat = YES;
    mylocationMarker.draggable = YES;
    mylocationMarker.groundAnchor = CGPointMake(0.5, 0.5);
    mylocationMarker.icon = [UIImage imageNamed:@"mendian"];
    mylocationMarker.map = self.mapView;
}

//Type argument 'NSInteger' (aka 'long') is neither an Objective-C object nor a block type
/**显示搜索控制器*/
- (void)fdShowResultViewController {
    self.resultControler.view.alpha = 0.0f;
    
    //显示搜索结果控制器
    //添加子视图控制器
    [self addChildViewController:self.resultControler];
    
    //添加子视图控制器的view
    self.resultControler.view.frame = CGRectMake(0, self.searchView.rb_bottom, SCREEN_WIDTH, 300);
    [self.view addSubview:self.resultControler.view];
    
    //reload data
    [self.resultControler.tableView reloadData];
    
    //动画
    [UIView animateWithDuration:0.5 animations:^{
        self.resultControler.view.alpha = 1.0f;
    } completion:^(BOOL finished) {
        [self.resultControler didMoveToParentViewController:self]; //已经移动到父视图控制器。
    }];
}

/**隐藏搜索控制器*/
- (void)fdHideResultViewController {
    [self.resultControler willMoveToParentViewController:nil];
    
    [UIView animateWithDuration:0.45 animations:^{
        //透明度为0.0f
        self.resultControler.view.alpha = 0.0f;
    } completion:^(BOOL finished) {
        //移除子视图控制器de view
        [self.resultControler.view removeFromSuperview];
        //移除子视图控制器
        [self.resultControler removeFromParentViewController];
    }];
}


#pragma mark - 2019-2-26装用于判断是否在配送范围之内的数据

#pragma mark - 判断
//GMSGeometryContainsLocation
@end
